package com.nfd.my_maven_plugin;

import java.io.File;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

@Mojo(name = "count" , defaultPhase =  LifecyclePhase.PACKAGE)
public class MyPlugin extends AbstractMojo{

	private final String DEFAULT_SUFFIX = ".java";
	
	@Parameter(property = "filePath",defaultValue = "${basedir}")
	private String filePath;
	
	@Parameter(property = "suffix",defaultValue = DEFAULT_SUFFIX)
	private String suffix;
	
	public void execute() throws MojoExecutionException, MojoFailureException {
		getLog().info("filePath:" + filePath);
		getLog().info("suffix:" + suffix);
		
		File file = new File(filePath);
		try {
			getLog().info("files:" + countFiles(file, suffix));
		} catch (Exception e) {
			getLog().error(e);
		}
	};

	/**
	 * 计算文件数目
	 * @param file
	 * @param suffix
	 * @return
	 */
	private int countFiles(File file,String suffix){
		int count = 0;
		if(file.isDirectory()){
			count += countDirectory(count, file);
		}else if(file.isFile()){
			String name = file.getName();
			if(name.endsWith(suffix)){
				getLog().info("find file: " + file.getAbsolutePath());
				return 1;
			}
		}
		
		return count;
	}
	
	
	/**
	 * 计算文件夹下文件数目
	 * @param nowCount
	 * @param file
	 * @return
	 */
	private int countDirectory(int nowCount,File file){
		File[] files = file.listFiles();
		if(files == null){
			return nowCount;
		}
		for(File oneFile: files){
			nowCount += countFiles(oneFile,suffix);
		}
		return nowCount;
	}
}
